package com.ruoyi.pingan.fymodule.separateSetting.storesetting.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.pingan.enums.CommonSortOrderEnum;
import com.ruoyi.pingan.exception.CommonException;
import com.ruoyi.pingan.fymodule.plugins.entity.SxoPluginsShop;
import com.ruoyi.pingan.fymodule.plugins.service.ISxoPluginsShopService;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.entity.FywCategoryTemplate;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.service.FywCategoryTemplateService;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.entity.CategoryTemplateDto;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.entity.FywStoreSetting;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.entity.ShopInfoDto;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.entity.ShopInfoSettingRsp;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.mapper.FywStoreSettingMapper;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.param.*;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.service.FywStoreSettingService;
import com.ruoyi.pingan.page.CommonPageRequest;
import com.ruoyi.pingan.util.CommonDownloadUtil;
import com.ruoyi.pingan.util.CommonResponseUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 商家分账设置表Service接口实现类
 *
 * @author zjf
 * @date  2025/07/29 17:00
 **/
@Service
public class FywStoreSettingServiceImpl extends ServiceImpl<FywStoreSettingMapper, FywStoreSetting> implements FywStoreSettingService {


    @Autowired
    private FywCategoryTemplateService fywCategoryTemplateService;

    @Autowired
    private ISxoPluginsShopService iSxoPluginsShopService;

    @Override
    public Page<FywStoreSetting> page(FywStoreSettingPageParam fywStoreSettingPageParam) {
        QueryWrapper<FywStoreSetting> queryWrapper = new QueryWrapper<FywStoreSetting>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(fywStoreSettingPageParam.getSortField(), fywStoreSettingPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(fywStoreSettingPageParam.getSortOrder());
            queryWrapper.orderBy(true, fywStoreSettingPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(fywStoreSettingPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(FywStoreSetting::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public ShopInfoSettingRsp newShopInfo(FywStoreSettingNewParam fywStoreSettingNewParam) {

        ShopInfoSettingRsp shopInfoSettingRsp = new ShopInfoSettingRsp();
        List<ShopInfoDto>  shopInfoList = new ArrayList<>();

        //取商家信息
        QueryWrapper<SxoPluginsShop> queryWrapper = new QueryWrapper<SxoPluginsShop>().checkSqlInjection();
        queryWrapper.lambda().eq(SxoPluginsShop::getStatus, 2);
        List<SxoPluginsShop> shopList =  iSxoPluginsShopService.list(queryWrapper);
        for(SxoPluginsShop sxoPluginsShop:shopList){
            ShopInfoDto shopInfoDto = new ShopInfoDto();
            shopInfoDto.setStoreId(sxoPluginsShop.getId());
            shopInfoDto.setShopName(sxoPluginsShop.getCompanyName());
            shopInfoDto.setStoreName(sxoPluginsShop.getName());
            shopInfoDto.setIsDefault("0");
            shopInfoList.add(shopInfoDto);
        }

        List<CategoryTemplateDto> TemplateList = new ArrayList<>();


        //取模版信息
        List<FywCategoryTemplate> fywCategoryTemplateList = fywCategoryTemplateService.list();

        for(FywCategoryTemplate fywCategoryTemplate :fywCategoryTemplateList){

            CategoryTemplateDto categoryTemplateDto = new CategoryTemplateDto();
            BeanUtil.copyProperties(fywCategoryTemplate, categoryTemplateDto);
            TemplateList.add(categoryTemplateDto);
        }
        shopInfoSettingRsp.setShopInfoList(shopInfoList);
        shopInfoSettingRsp.setTemplateList(TemplateList);
        return shopInfoSettingRsp;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(FywStoreSettingAddParam fywStoreSettingAddParam) {

        //判断模板是否有值，如果没值默认取默认模板
        String categoryName = fywStoreSettingAddParam.getCategoryName();
        if(categoryName==null||categoryName==""){
            QueryWrapper<FywCategoryTemplate> queryWrapper = new QueryWrapper<FywCategoryTemplate>().checkSqlInjection();
            queryWrapper.lambda().eq(FywCategoryTemplate::getIsDefault, "1");
            FywCategoryTemplate fywCategoryTemplate =  fywCategoryTemplateService.getOne(queryWrapper);
            fywStoreSettingAddParam.setCategoryId(fywCategoryTemplate.getId());
            fywStoreSettingAddParam.setCategoryName(fywCategoryTemplate.getCategoryName());
        }
        //先判断是否存在，如果存在返回已存在
        FywStoreSetting fywStoreSetting = BeanUtil.toBean(fywStoreSettingAddParam, FywStoreSetting.class);
        this.save(fywStoreSetting);
    }

    @Override
    public boolean checkShop(FywStoreSettingAddParam fywStoreSettingAddParam) {

        String storeName = fywStoreSettingAddParam.getStoreName();
        QueryWrapper<FywStoreSetting> queryWrapper = new QueryWrapper<FywStoreSetting>().checkSqlInjection();
        queryWrapper.lambda().eq(FywStoreSetting::getStoreName, storeName);
        List<FywStoreSetting> resultList = this.list(queryWrapper);
        if(resultList.size()>0){
            return false;
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(FywStoreSettingEditParam fywStoreSettingEditParam) {
        FywStoreSetting fywStoreSetting = this.queryEntity(fywStoreSettingEditParam.getId());
        BeanUtil.copyProperties(fywStoreSettingEditParam, fywStoreSetting);
        this.updateById(fywStoreSetting);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<FywStoreSettingIdParam> fywStoreSettingIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(fywStoreSettingIdParamList, FywStoreSettingIdParam::getId));
    }

    @Override
    public FywStoreSetting detail(FywStoreSettingIdParam fywStoreSettingIdParam) {
        return this.queryEntity(fywStoreSettingIdParam.getId());
    }



    @Override
    public void downloadImportTemplate(HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<FywStoreSettingEditParam> dataList = CollectionUtil.newArrayList();
         String fileName = "商家分账设置表导入模板_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), FywStoreSettingEditParam.class).sheet("商家分账设置表").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 商家分账设置表导入模板下载失败：", e);
         CommonResponseUtil.renderError(response, "商家分账设置表导入模板下载失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject importData(MultipartFile file) {
        try {
            int successCount = 0;
            int errorCount = 0;
            JSONArray errorDetail = JSONUtil.createArray();
            // 创建临时文件
            File tempFile = FileUtil.writeBytes(file.getBytes(), FileUtil.file(FileUtil.getTmpDir() +
                    FileUtil.FILE_SEPARATOR + "fywStoreSettingImportTemplate.xlsx"));
            // 读取excel
            List<FywStoreSettingEditParam> fywStoreSettingEditParamList =  EasyExcel.read(tempFile).head(FywStoreSettingEditParam.class).sheet()
                    .headRowNumber(1).doReadSync();
            List<FywStoreSetting> allDataList = this.list();
            for (int i = 0; i < fywStoreSettingEditParamList.size(); i++) {
                JSONObject jsonObject = this.doImport(allDataList, fywStoreSettingEditParamList.get(i), i);
                if(jsonObject.getBool("success")) {
                    successCount += 1;
                } else {
                    errorCount += 1;
                    errorDetail.add(jsonObject);
                }
            }
            return JSONUtil.createObj()
                    .set("totalCount", fywStoreSettingEditParamList.size())
                    .set("successCount", successCount)
                    .set("errorCount", errorCount)
                    .set("errorDetail", errorDetail);
        } catch (Exception e) {
            log.error(">>> 商家分账设置表导入失败：", e);
            throw new CommonException("商家分账设置表导入失败");
        }
    }

    public JSONObject doImport(List<FywStoreSetting> allDataList, FywStoreSettingEditParam fywStoreSettingEditParam, int i) {
        String id = fywStoreSettingEditParam.getId();
        if(ObjectUtil.hasEmpty(id)) {
            return JSONUtil.createObj().set("index", i + 1).set("success", false).set("msg", "必填字段存在空值");
        } else {
            try {
                int index = CollStreamUtil.toList(allDataList, FywStoreSetting::getId).indexOf(fywStoreSettingEditParam.getId());
                FywStoreSetting fywStoreSetting;
                boolean isAdd = false;
                if(index == -1) {
                    isAdd = true;
                    fywStoreSetting = new FywStoreSetting();
                } else {
                    fywStoreSetting = allDataList.get(index);
                }
                BeanUtil.copyProperties(fywStoreSettingEditParam, fywStoreSetting);
                if(isAdd) {
                    allDataList.add(fywStoreSetting);
                } else {
                    allDataList.remove(index);
                    allDataList.add(index, fywStoreSetting);
                }
                this.saveOrUpdate(fywStoreSetting);
                return JSONUtil.createObj().set("success", true);
            } catch (Exception e) {
              log.error(">>> 数据导入异常：", e);
              return JSONUtil.createObj().set("success", false).set("index", i + 1).set("msg", "数据导入异常");
            }
        }
    }

    @Override
    public FywStoreSetting queryEntity(String id) {
        FywStoreSetting fywStoreSetting = this.getById(id);
        if(ObjectUtil.isEmpty(fywStoreSetting)) {
            throw new CommonException("商家分账设置表不存在，id值为：{}", id);
        }
        return fywStoreSetting;
    }

    @Override
    public void exportData(List<FywStoreSettingIdParam> fywStoreSettingIdParamList, HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<FywStoreSettingEditParam> dataList;
         if(ObjectUtil.isNotEmpty(fywStoreSettingIdParamList)) {
            List<String> idList = CollStreamUtil.toList(fywStoreSettingIdParamList, FywStoreSettingIdParam::getId);
            dataList = BeanUtil.copyToList(this.listByIds(idList), FywStoreSettingEditParam.class);
         } else {
            dataList = BeanUtil.copyToList(this.list(), FywStoreSettingEditParam.class);
         }
         String fileName = "商家分账设置表_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), FywStoreSettingEditParam.class).sheet("商家分账设置表").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 商家分账设置表导出失败：", e);
         CommonResponseUtil.renderError(response, "商家分账设置表导出失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }
}
